<template>
  <div class="mysql-monitor-root">
    <!-- 概览卡片区 -->
    <a-row :gutter="[16, 16]" class="overview-row">
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">数据库版本</div>
          <div class="card-value">{{ safeText(databaseInfo?.databaseProductVersion) }}</div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">数据库名</div>
          <div class="card-value">{{ safeText(databaseInfo?.dbName) }}</div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">当前用户</div>
          <a-tooltip :title="safeText(databaseInfo?.userName)">
            <div class="card-value ellipsis">{{ safeText(databaseInfo?.userName) }}</div>
          </a-tooltip>
        </a-card></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">当前连接数</div>
          <div class="card-value">{{ safeText(databaseInfo?.threadsConnected) }}</div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">最大连接数</div>
          <div class="card-value">{{ safeText(databaseInfo?.maxUsedConnections) }}</div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">活跃会话数</div>
          <div class="card-value">{{ safeText(databaseInfo?.activeSessionCount) }}</div></a-card
        ></a-col
      >
    </a-row>
    <a-row :gutter="[16, 16]" class="overview-row" style="margin-top: 0">
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">QPS</div>
          <div class="card-value">
            {{ safeText(performanceSummary?.QPS) ? formatNumber(performanceSummary.QPS) : '-' }}
          </div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">TPS</div>
          <div class="card-value">
            {{ safeText(performanceSummary?.TPS) ? formatNumber(performanceSummary.TPS) : '-' }}
          </div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">慢查询数</div>
          <div class="card-value">{{ safeText(performanceSummary?.slowQueries) }}</div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">表数量</div>
          <div class="card-value">
            {{ safeText(databaseInfo?.tableCount) ?? safeText(tables?.length) }}
          </div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">索引数量</div>
          <div class="card-value">
            {{ safeText(databaseInfo?.indexCount) ?? safeText(indexes?.length) }}
          </div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">触发器数量</div>
          <div class="card-value">{{ safeText(databaseInfo?.triggerCount) }}</div></a-card
        ></a-col
      >
    </a-row>
    <a-row :gutter="[16, 16]" class="overview-row" style="margin-top: 0">
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">事件数量</div>
          <div class="card-value">{{ safeText(databaseInfo?.eventCount) }}</div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">数据库大小</div>
          <div class="card-value">
            {{ safeText(formatSize(databaseInfo?.databaseSizeBytes)) }}
          </div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">运行时长(s)</div>
          <div class="card-value">{{ safeText(formatUptime(databaseInfo?.uptime)) }}</div></a-card
        ></a-col
      >
      <a-col :span="4"
        ><a-card class="overview-card" :bordered="false"
          ><div class="card-title">驱动</div>
          <a-tooltip :title="safeText(databaseInfo?.driverName)">
            <div class="card-value ellipsis">{{ safeText(databaseInfo?.driverName) }}</div>
          </a-tooltip>
        </a-card></a-col
      >
      <a-col :span="4">
        <a-card class="overview-card" :bordered="false">
          <div class="card-title">驱动版本</div>
          <a-tooltip :title="safeText(databaseInfo?.driverVersion)">
            <div
              class="card-value ellipsis"
              @click="showDetail('驱动版本', safeText(databaseInfo?.driverVersion))"
              style="cursor: pointer"
            >
              {{ ellipsisText(safeText(databaseInfo?.driverVersion), 32) }}
            </div>
          </a-tooltip>
        </a-card>
      </a-col>
      <a-col :span="4">
        <a-card class="overview-card" :bordered="false">
          <div class="card-title">JDBC URL</div>
          <a-tooltip :title="safeText(databaseInfo?.url)">
            <div
              class="card-value ellipsis"
              style="font-size: 12px; cursor: pointer"
              @click="showDetail('JDBC URL', safeText(databaseInfo?.url))"
            >
              {{ ellipsisText(safeText(databaseInfo?.url), 32) }}
            </div>
          </a-tooltip>
        </a-card>
      </a-col>
    </a-row>

    <!-- 统计图区域（新增） -->
    <a-row :gutter="[16, 16]" class="group-row">
      <!-- 连接统计 -->
      <a-col :span="8">
        <a-card class="group-card" title="连接统计">
          <v-chart :option="connectionBarOption" autoresize style="height: 120px" />
          <div class="stat-row">
            <span class="stat-label">当前连接数</span>
            <span class="stat-value">{{ safeText(databaseInfo.threadsConnected) }}</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">最大连接数</span>
            <span class="stat-value">{{ safeText(databaseInfo.maxUsedConnections) }}</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">活跃会话数</span>
            <span class="stat-value">{{ safeText(databaseInfo.activeSessionCount) }}</span>
          </div>
        </a-card>
      </a-col>
      <!-- 性能统计 -->
      <a-col :span="8">
        <a-card class="group-card" title="性能统计">
          <v-chart :option="performanceLineOption" autoresize style="height: 120px" />
          <div class="stat-row">
            <span class="stat-label">QPS</span>
            <span class="stat-value">{{ safeText(performanceSummary.QPS) }}</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">TPS</span>
            <span class="stat-value">{{ safeText(performanceSummary.TPS) }}</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">慢查询数</span>
            <span class="stat-value">{{ safeText(performanceSummary.slowQueries) }}</span>
          </div>
        </a-card>
      </a-col>
      <!-- 表空间统计 -->
      <a-col :span="8">
        <a-card class="group-card" title="表空间统计">
          <v-chart :option="tablePieOption" autoresize style="height: 120px" />
          <div class="stat-row">
            <span class="stat-label">表数量</span>
            <span class="stat-value">{{
              safeText(databaseInfo.tableCount) ?? safeText(tables.length)
            }}</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">索引数量</span>
            <span class="stat-value">{{ safeText(databaseInfo.indexCount) ?? '-' }}</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">数据库大小</span>
            <span class="stat-value">{{
              safeText(formatSize(databaseInfo.databaseSizeBytes))
            }}</span>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 进程列表 -->
    <a-card class="section-card" :bordered="false" style="margin-top: 24px">
      <div class="section-title">进程列表</div>
      <a-table
        :dataSource="processes"
        :columns="processColumns"
        size="small"
        :pagination="false"
        rowKey="id"
        :scroll="{ x: 900, y: 260 }"
        :locale="{ emptyText: '暂无进程数据' }"
      />
    </a-card>

    <!-- 表空间与表统计 -->
    <a-card class="section-card" :bordered="false" style="margin-top: 24px">
      <div class="section-title">表空间与表统计</div>
      <a-table
        :dataSource="tables"
        :columns="tableColumns"
        size="small"
        :pagination="false"
        rowKey="name"
        :scroll="{ x: 1200, y: 260 }"
        :locale="{ emptyText: '暂无表数据' }"
      />
    </a-card>

    <!-- 其余详情折叠区 -->
    <a-card class="section-card" :bordered="false" style="margin-top: 24px">
      <a-collapse ghost>
        <a-collapse-panel key="innodb" header="InnoDB 状态 (部分)">
          <pre class="innodb-status">{{ safeText(data?.innodbStatus?.slice(0, 2000)) }}</pre>
        </a-collapse-panel>
        <a-collapse-panel key="indexes" header="索引信息">
          <a-table
            :dataSource="groupedIndexes"
            :columns="[{ title: '表名', dataIndex: 'table', key: 'table' }]"
            :expandable="{
              expandedRowRender: record =>
                h('div', {}, [
                  h('a-table', {
                    dataSource: record.children,
                    columns: indexColumns.filter(col => col.dataIndex !== 'table'),
                    size: 'small',
                    pagination: false,
                    rowKey: 'indexName',
                    style: 'margin:0;background:none;',
                  }),
                ]),
              rowExpandable: record => record.children.length > 0,
            }"
            rowKey="table"
            size="small"
            :pagination="false"
            :scroll="{ x: 900, y: 180 }"
          />
        </a-collapse-panel>
        <a-collapse-panel key="primaryKeys" header="主键信息">
          <a-table
            :dataSource="groupedPrimaryKeys"
            :columns="[{ title: '表名', dataIndex: 'table', key: 'table' }]"
            :expandable="{
              expandedRowRender: record =>
                h('div', {}, [
                  h('a-table', {
                    dataSource: record.children,
                    columns: pkColumns.filter(col => col.dataIndex !== 'table'),
                    size: 'small',
                    pagination: false,
                    rowKey: 'pkName',
                    style: 'margin:0;background:none;',
                  }),
                ]),
              rowExpandable: record => record.children.length > 0,
            }"
            rowKey="table"
            size="small"
            :pagination="false"
            :scroll="{ x: 600, y: 120 }"
          />
        </a-collapse-panel>
        <a-collapse-panel key="users" header="数据库用户">
          <a-table
            :dataSource="users"
            :columns="userColumns"
            size="small"
            :pagination="false"
            rowKey="user"
            :scroll="{ x: 400, y: 120 }"
          />
        </a-collapse-panel>
        <a-collapse-panel key="raw" header="原始数据(JSON)">
          <pre style="max-height: 300px; overflow: auto; color: #b2f7ef">{{
            safeText(JSON.stringify(data, null, 2))
          }}</pre>
        </a-collapse-panel>
      </a-collapse>
    </a-card>

    <a-modal
      v-model:visible="detailModal.visible"
      :title="detailModal.title"
      :footer="null"
      width="600px"
      centered
    >
      <pre
        style="white-space: pre-wrap; word-break: break-all; max-height: 400px; overflow: auto"
        >{{ detailModal.content }}</pre
      >
    </a-modal>
  </div>
</template>

<script setup lang="ts">
  import { ref, computed, onMounted, onUnmounted, onActivated, onDeactivated, h } from 'vue'
  import { getMysqlMonitorStatistics } from '@/api/guanliyuanmokuaijiekou'

  const data = ref<any>(null)

  // 新增：安全文本处理
  function safeText(val: any) {
    return val === undefined || val === null || val === '' ? '暂无数据' : val
  }
  // 新增：安全数值格式化
  function formatNumber(val: any, digits = 2) {
    return typeof val === 'number' ? val.toFixed(digits) : '暂无数据'
  }

  const databaseInfo = computed(() => data.value?.databaseInfo || {})
  const performanceSummary = computed(() => data.value?.performanceSummary || {})

  let timer: ReturnType<typeof setInterval> | null = null

  const processes = computed(() => data.value?.processes || [])
  const tables = computed(() => data.value?.tables || [])
  const primaryKeys = computed(() => data.value?.primaryKeys || [])
  const indexes = computed(() => data.value?.indexes || [])
  const users = computed(() => data.value?.users || [])

  function formatSize(val: number | undefined) {
    if (!val) return '-'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
    const i = Math.floor(Math.log(val) / Math.log(k))
    return parseFloat((val / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
  }
  function formatUptime(seconds: number | undefined) {
    if (!seconds) return '-'
    const h = Math.floor(seconds / 3600)
    const m = Math.floor((seconds % 3600) / 60)
    const s = seconds % 60
    return `${h}小时${m}分${s}秒`
  }

  const fetchData = async () => {
    try {
      const res = await getMysqlMonitorStatistics()
      if (res.data.code === 200) {
        data.value = res.data.data || {}
      }
    } catch {}
  }

  function startTimer() {
    if (timer) return
    fetchData()
    timer = setInterval(fetchData, 1000)
  }
  function stopTimer() {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
  }

  onMounted(startTimer)
  onActivated(startTimer)
  onUnmounted(stopTimer)
  onDeactivated(stopTimer)

  const processColumns = [
    { title: 'ID', dataIndex: 'id', width: 60 },
    { title: '用户', dataIndex: 'user', width: 100 },
    { title: '主机', dataIndex: 'host', width: 140 },
    { title: '数据库', dataIndex: 'db', width: 120 },
    { title: '命令', dataIndex: 'command', width: 100 },
    { title: '状态', dataIndex: 'state', width: 180 },
    { title: '耗时(s)', dataIndex: 'time', width: 80 },
    { title: 'SQL/信息', dataIndex: 'info', width: 200, ellipsis: true },
  ]
  const tableColumns = [
    { title: '表名', dataIndex: 'name', width: 140 },
    { title: '引擎', dataIndex: 'engine', width: 80 },
    { title: '行数', dataIndex: 'rows', width: 80 },
    { title: '数据大小', dataIndex: 'dataLength', width: 100 },
    { title: '索引大小', dataIndex: 'indexLength', width: 100 },
    { title: '自增ID', dataIndex: 'autoIncrement', width: 120 },
    { title: '创建时间', dataIndex: 'createTime', width: 160 },
    { title: '更新时间', dataIndex: 'updateTime', width: 160 },
    { title: '字符集', dataIndex: 'collation', width: 120 },
    { title: '备注', dataIndex: 'comment', width: 160, ellipsis: true },
  ]
  const indexColumns = [
    { title: '表名', dataIndex: 'table', width: 120 },
    { title: '索引名', dataIndex: 'indexName', width: 120 },
    { title: '列名', dataIndex: 'columnName', width: 120 },
    {
      title: '唯一',
      dataIndex: 'nonUnique',
      width: 60,
      customRender: ({ text }: { text: boolean }) => (text ? '否' : '是'),
    },
    { title: '类型', dataIndex: 'indexType', width: 80 },
    { title: '顺序', dataIndex: 'ascOrDesc', width: 60 },
    { title: '基数', dataIndex: 'cardinality', width: 80 },
  ]
  const pkColumns = [
    { title: '表名', dataIndex: 'table', width: 120 },
    { title: '主键名', dataIndex: 'pkName', width: 120 },
    { title: '列名', dataIndex: 'columnName', width: 120 },
    { title: '序号', dataIndex: 'keySeq', width: 60 },
  ]
  const userColumns = [
    { title: '用户', dataIndex: 'user', width: 120 },
    { title: '主机', dataIndex: 'host', width: 120 },
  ]

  // 分组：索引信息
  const groupedIndexes = computed(() => {
    const groups: Record<string, any[]> = {}
    indexes.value.forEach((idx: any) => {
      if (!groups[idx.table]) groups[idx.table] = []
      groups[idx.table].push(idx)
    })
    return Object.keys(groups).map(table => ({
      table,
      children: groups[table],
    }))
  })
  // 分组：主键信息
  const groupedPrimaryKeys = computed(() => {
    const groups: Record<string, any[]> = {}
    primaryKeys.value.forEach((pk: any) => {
      if (!groups[pk.table]) groups[pk.table] = []
      groups[pk.table].push(pk)
    })
    return Object.keys(groups).map(table => ({
      table,
      children: groups[table],
    }))
  })

  // 统计图option
  // 连接统计 柱状图
  const connectionBarOption = computed(() => {
    return {
      tooltip: { trigger: 'axis' },
      xAxis: { type: 'category', data: ['当前连接数', '最大连接数', '活跃会话数'] },
      yAxis: { type: 'value' },
      series: [
        {
          data: [
            Number(databaseInfo.value.threadsConnected || 0),
            Number(databaseInfo.value.maxUsedConnections || 0),
            Number(databaseInfo.value.activeSessionCount || 0),
          ],
          type: 'bar',
          itemStyle: { color: '#1890ff' },
          barWidth: 28,
        },
      ],
      grid: { left: 20, right: 20, top: 30, bottom: 20 },
    }
  })
  // 性能统计 折线图
  const performanceLineOption = computed(() => {
    return {
      tooltip: { trigger: 'axis' },
      legend: { data: ['QPS', 'TPS', '慢查询'] },
      xAxis: { type: 'category', data: ['当前'] },
      yAxis: { type: 'value' },
      series: [
        {
          name: 'QPS',
          type: 'line',
          data: [Number(performanceSummary.value.QPS || 0)],
          itemStyle: { color: '#0057b8' },
        },
        {
          name: 'TPS',
          type: 'line',
          data: [Number(performanceSummary.value.TPS || 0)],
          itemStyle: { color: '#36cfc9' },
        },
        {
          name: '慢查询',
          type: 'line',
          data: [Number(performanceSummary.value.slowQueries || 0)],
          itemStyle: { color: '#faad14' },
        },
      ],
      grid: { left: 20, right: 20, top: 30, bottom: 20 },
    }
  })
  // 表空间统计 饼图
  const tablePieOption = computed(() => {
    const tbs = tables.value || []
    return {
      tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
      legend: { show: false },
      series: [
        {
          type: 'pie',
          radius: ['60%', '80%'],
          label: { show: true, formatter: '{b}: {d}%' },
          data: tbs.map((tb: any) => ({ value: Number(tb.rows || 0), name: tb.name })),
        },
      ],
    }
  })

  // 省略长文本
  function ellipsisText(text: string, max: number = 32) {
    if (!text) return ''
    return text.length > max ? text.slice(0, max) + '...' : text
  }
  // 弹窗详情
  const detailModal = ref({ visible: false, title: '', content: '' })
  function showDetail(title: string, content: string) {
    detailModal.value.title = title
    detailModal.value.content = content
    detailModal.value.visible = true
  }
</script>

<style scoped>
  .mysql-monitor-root {
    padding: 0 8px;
    background: #f5f6fa;
    min-height: 100vh;
  }
  .overview-row {
    margin-bottom: 0;
  }
  .overview-card,
  .section-card {
    background: var(--theme-surface) !important;
    border: 1px solid var(--theme-border) !important;
    box-shadow: 0 2px 8px var(--theme-shadow);
    border-radius: 12px !important;
    color: var(--theme-text) !important;
    transition: all 0.3s ease;
  }
  
  .card-title {
    color: var(--theme-primary);
    font-size: 15px;
    font-weight: 500;
    margin-bottom: 4px;
    line-height: 1.2;
    transition: color 0.3s ease;
  }
  
  .card-value {
    color: var(--theme-text);
    font-size: 15px;
    font-family: 'JetBrains Mono', 'Consolas', 'Roboto Mono', monospace;
    font-weight: bold;
    line-height: 1.3;
    text-align: left;
    word-break: break-all;
    max-width: 100%;
    min-width: 0;
    display: block;
    white-space: pre-line;
    transition: color 0.3s ease;
  }
  
  .section-title {
    color: var(--theme-primary);
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 12px;
    margin-top: 8px;
    letter-spacing: 1px;
    transition: color 0.3s ease;
  }
  
  .innodb-status {
    color: var(--theme-primary);
    font-size: 13px;
    background: var(--theme-background);
    border-radius: 8px;
    padding: 12px;
    max-height: 220px;
    overflow: auto;
    transition: all 0.3s ease;
  }
  
  :deep(.ant-table) {
    background: var(--theme-surface) !important;
    transition: all 0.3s ease;
  }
  
  :deep(.ant-table-thead > tr > th) {
    background: var(--theme-background) !important;
    color: var(--theme-primary) !important;
    font-weight: 500;
    font-size: 14px;
    transition: all 0.3s ease;
  }
  
  :deep(.ant-table-tbody > tr > td) {
    background: var(--theme-surface) !important;
    color: var(--theme-text) !important;
    font-size: 13px;
    white-space: pre-line !important;
    word-break: break-all !important;
    transition: all 0.3s ease;
  }
  
  :deep(.ant-table-row:hover) > td {
    background: var(--theme-primary) !important;
    color: var(--theme-surface) !important;
  }
  
  .group-row {
    margin-top: 8px;
  }
  
  .group-card {
    background: var(--theme-surface) !important;
    border: 1px solid var(--theme-border) !important;
    box-shadow: 0 2px 8px var(--theme-shadow);
    border-radius: 12px !important;
    color: var(--theme-text) !important;
    min-height: 120px;
    padding: 8px 10px;
    transition: all 0.3s ease;
  }
  
  .stat-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
    font-size: 14px;
  }
  
  .stat-label {
    color: var(--theme-textSecondary);
    transition: color 0.3s ease;
  }
  
  .stat-value {
    color: var(--theme-primary);
    font-family: 'JetBrains Mono', 'Consolas', 'Roboto Mono', monospace;
    word-break: break-all;
    transition: color 0.3s ease;
  }
  
  .ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    cursor: pointer;
  }

  /* 确保所有元素都使用主题色 */
  .mysql-monitor-root * {
    transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease, box-shadow 0.3s ease;
  }
</style>
